<?php
namespace app\admin\controller;

use think\Db;
use app\admin\model\MessageContent as MessageContentModel;
use app\admin\model\Message as MessageModel;

class Message extends Base {

    private $uid;

    public function _initialize() 
    {
        $this->uid = session('userinfo.id');
        parent::_initialize();
    }

    /*
     * 后台站内信列表-我接收的站内信
     */
    public function myMessageList() 
    {
        $uid = $this->uid;  //接收人
        $tab_type = input('tab_type', 1);
        $where = array();
        $where['message.rec_uid'] = $uid;
        $where['message.statue'] = array('neq', 4);
        $where['message_content.deletetag'] = 0;
        $where['message_content.send_status'] = 1;
        $where['message_content.send_type'] = $tab_type;
        $messageContentList = Db::name('message_content')
                ->field('message_content.*, message.id AS m_id, message.statue')
                ->join('message', 'message_content.id = message.mc_id', 'left')
                ->where($where)
                ->order('message_content.send_time desc')
                ->paginate(config('paginate.list_rows'), false, ['query' => get_query()]);
        $page = $messageContentList->render();
        $messageStatus = array(0 => '未读', 1 => '已读');
        $this->assign('messageStatus', $messageStatus);
        $this->assign('messageContentList', $messageContentList);
        $this->assign('page', $page);
        $this->assign('tab_type', $tab_type);

        return $this->fetch();
    }
    
    /*
     * 后台站内信列表-我发送的站内信
     */
    public function mySendMessageList() 
    {
        $uid = $this->uid;  //发送人
        $tab_type = input('tab_type', 1);
        $cond_where = array();
        $cond_where['send_uid'] = $uid;
        $cond_where['deletetag'] = 0;
        $cond_where['send_type'] = $tab_type;
        $messageContentList = Db::name('message_content')
                ->where($cond_where)
                ->order('send_time desc')
                ->paginate(config('paginate.list_rows'), false, ['query' => get_query()]);
        $page = $messageContentList->render();
        $messageStatus = array(0 => '未发送', 1 => '已发送');
        $this->assign('messageStatus', $messageStatus);
        $this->assign('messageContentList', $messageContentList);
        $this->assign('page', $page);
        $this->assign('tab_type', $tab_type);

        return $this->fetch();
    }

    /*
     * 发送通知公告
     */
    public function sendMessage() 
    {
         //获得运营公司所有部门
        $dept_list = Db::name('dept')
                ->where(array('org_id' => 1))
                ->field('id,pid,name')
                ->select();
        //获得运营公司所有有效人员
        $where_cond = array(
            'org_id' => 1,
            'isvalid' => 1,
        );
        $all_user_list = Db::name('user')
                ->where($where_cond)
                ->field('id,dept_id,name')
                ->select();
        $tab_type = input('tab_type', 1);
        $action_type = input('action_type');

        if($action_type == 'pub_message'){

            if (!request()->isAjax()){
                $this->error('提交方式不正确');
            }
            $send_uid = session('userinfo.id');//发送人
            $send_type = input('send_type', 0, 'intval');//发送消息类型 1 通知消息 2 站内信
            $title = input('message_title', '', 'htmlspecialchars');//消息标题
            $contents = input('message_content', '', 'htmlspecialchars');//消息内容

            if(empty($contents)){
                $this->error('内容不能为空');
            }
            $messeageContentModel=new MessageContentModel;
            $messeageContentModel->startTrans();
            $mcId = $messeageContentModel->addMessageContent($send_uid, $send_type, $title, $contents,1);

            //添加用户消息记录
            if ( $mcId > 0 ) {
                if ($send_type == 1) {  //全体站内信公告   
                    $uid_arr = array();
                    $uid_arr = $all_user_list;
                     if (!empty($uid_arr)) {
                        foreach ($uid_arr  as $key => $value) {
                            $recUids[] = $value['id'];
                        }
                        unset($uid_arr);
                    } else {
                        $messeageContentModel->rollback();  //回滚事务
                        $this->error('发送失败，未查到符合条件的用户');
                    }
                }else if ( $send_type == 2 ) {
                    $recDeptids = input('hidden_dept_id/a');//按照部门发送站内信
                    $recUids = input('hidden_user_id/a');//接收用户 
                    if(is_array($recDeptids) && !empty($recDeptids)){
                        $uid_arr = array();
                        $uid_arr = Db::name('user')
                            ->where($where_cond)
                            ->where('dept_id','in',$recDeptids)
                            ->field('id')
                            ->select();
                        if (!empty($uid_arr)) {
                            foreach ($uid_arr  as $key => $value) {
                                $recUids[] = $value['id'];
                            }
                            unset($uid_arr);
                        } else {
                            $messeageContentModel->rollback();  //回滚事务
                            $this->error('发送失败，未查到符合条件的用户');
                        }
                    }else if(is_array($recUids) && !empty($recUids)){
                        $recUids = array_unique($recUids);
                    }else{
                        $this->error('发送失败，请选择需要发布的部门或者人员名单');
                    }
                }
                
            }
            $dataList = array();

            if ( !empty($recUids) ) {
                $i = 0;
                foreach ($recUids as $key => $value ) {
                    $dataList[$i]['mc_id'] = $mcId;
                    $dataList[$i]['rec_uid'] = intval($value);
                    $dataList[$i]['statue'] = 0;
                    $i ++;
                }
                $messeage=new MessageModel;
                $result =  $messeage->saveAll($dataList);   
            } 
            
            if( $result){
                $messeageContentModel->commit(); //提交事务   
                $this->success('发送成功', url('Message/mysendmessagelist', array('tab_type' => $send_type)));
            }else{
                $messeageContentModel->rollback();//回滚事务
                $this->error('发送失败');
            }
        }
        /* 循环部门数据 */
        $deptListTemp = array();
        foreach ($dept_list as $key => $value) {
            $deptListTemp[$key]['id'] = $value['id'].'_dept';
            $deptListTemp[$key]['pid'] = $value['pid'].'_dept';
            $deptListTemp[$key]['name'] = $value['name'];
            $deptListInfo[$key]['id'] = $value['id'] ;
            $deptListInfo[$key]['pid'] = $value['pid'];
            $deptListInfo[$key]['name'] = $value['name'];
            $deptListTemp[$key]['chkDisabled'] = "true";     
        }
        foreach ($all_user_list as $key => $value) {
            $all_user_list[$key]['pid'] = $value['dept_id'].'_dept';
        }
        $deptListJson = json_encode($deptListInfo);
        $userListJson = json_encode(array_merge($deptListTemp, $all_user_list));
        $this->assign('deptListJson', $deptListJson);
        $this->assign('userListJson', $userListJson);
        $this->assign('tab_type', $tab_type);
        if ($tab_type==1) {
            return $this->fetch(); 
        } else {
            return $this->fetch("send_announcement"); 
        }
    }

    /*
     * 查看消息内容
     */
    public function viewMessageInfo() 
    {
        $messageId = input('param.messageId', 0, 'intval');
        $type = input('param.type'); //mylist表示我的消息，mysend表示我的发送
        if ($type == 'mylist') {//我的消息
            $messageInfo = Db::table('message_content')
                    ->join('message', 'message_content.id = message.mc_id', 'left')
                    ->where('message.id', $messageId)
                    ->find();
        } else {//已发消息
            $messageInfo = Db::table('message_content')
                    ->where('message_content.id', $messageId)
                    ->find();
        }
        
        $userInfo = array();
        if (!empty($messageInfo)) {
            $send_uid = $messageInfo['send_uid'];
            $userInfo = Db::table('user')->where('id', $send_uid)->find();
            //var_dump($userInfo);
            //exit;
            //更新消息为已读
            if ($type == 'mylist') {
                if ($messageInfo['statue'] == 0) {
                    Db::table('message')->where('id', $messageId)->update(['statue' => 1]);
                }
            }

            $messageInfo['contents'] = htmlspecialchars_decode($messageInfo['contents']);
        }
        $this->assign('messageInfo', $messageInfo);
        $this->assign('userInfo', $userInfo);
        return $this->fetch();
    }

    /*
     * 根据接收消息编号id删除消息
     */
    public function delMessageByMessageId() 
    {
        $messageId = input('message_id');
        $tab_type = input('tab_type');

        $del_result = false;
        $del_result = Db::name('message')->where('id', $messageId)->update(['statue' => 4]);

        if ($del_result) {
            $this->success('删除成功', url('Message/myMessageList', array('tab_type' => $tab_type)));
        } else {
            $this->error('删除失败', url('Message/myMessageList'));
        }
    }

    /*
     * 根据消息内容编号id删除消息内容
     */
    public function delMessageByConentId() 
    {
        $messageContentId = input('message_id');
        $tab_type = input('tab_type');

        $del_result = false;
        $del_result = Db::name('message_content')->where('id', $messageContentId)->update(['deletetag' => 1]);

        if ($del_result) {
            $this->success('删除成功', url('Message/mySendMessageList', array('tab_type' => $tab_type)));
        } else {
            $this->error('删除失败', url('Message/mySendMessageList'));
        }
    }

    /*
     * 编辑消息内容和标题
     */
    public function editMessageContent() 
    {
        $message_id = input('message_id', 0, 'intval');
        $action_type = input('action_type');
        if($action_type == 'edit_message'){
            if (!request()->isAjax()){
                $this->error('提交方式不正确');
            }
            $send_type = input('send_type',1);
            $data = array();
            $data['title'] = input('message_title', '', 'htmlspecialchars');//消息标题
            $data['contents'] = input('message_content', '', 'htmlspecialchars');//消息内容
            if(empty($data['contents'])){
                $this->error('内容不能为空');
            }
            $id = Db::table('message_content')->where('id', $message_id)->update($data);
            if( $id){
                $this->success("编辑消息成功！" ,url('Message/mySendMessageList', array('tab_type' => $send_type)));
            }else{
                $this->success("编辑消息失败！");
            }
        }
        $messageInfo = Db::table('message_content')
                    ->where('message_content.id', $message_id)
                    ->find();
        $messageInfo['contents'] = htmlspecialchars_decode($messageInfo['contents']);
        $this->assign('messageInfo', $messageInfo);
        return $this->fetch();
    }
    
     /**
     * 异步根据用户姓名获取用户信息
     */
    public function ajaxGetUserInfoByName() 
    {
        $search_key = input('term'); //搜索字段
        $where_cond = array(
            'user.org_id' => 1,
            'user.isvalid' => 1,
        );
        
        $user = Db::name('user')
                ->join('dept',"dept.id = user.dept_id")
                ->where('user.name|user.name_py','like',$search_key.'%')
                ->where( $where_cond)
                ->field('user.id,dept.name dept_name,user.name')
                ->select();

        if (empty($user)) {
            $user[0]['id'] = 0;
            $user[0]['name'] = '无符合条件的用户信息';
        }
	return(json_encode($user));
    }
    
    /*
     * 根据类型获取未读消息列表信息
     * @param int $type 消息类型
     * @return json 消息列表数据
     */
    public function ajaxGetUnreadListByType()
    {   
        $userInfo = session('userinfo');
        $userId = $userInfo['id'];
        $type = intval(input('param.type')) > 0 ? intval(input('type')) : 1;
        $limit = intval(input('param.show_num')) > 0 ? intval(input('show_num')) : 10;
        
        $cond_where = array();
        $cond_where['m.rec_uid'] = $userId;
        $cond_where['m.statue'] = array('eq', 0);
        $cond_where['c.deletetag'] = 0;
        $cond_where['c.send_status'] = 1;
        $cond_where['c.send_type'] = $type;
        
        $cond_order = array('send_time' => 'desc');
        $search_field_arr = array('m.id', 'm.mc_id', 'm.statue', 'c.title','c.send_status', 'c.send_time', 'c.send_type');
        $messageContentList = array();
        $messageContentList =  Db::name('message')
                            ->alias('m')
                            ->field($search_field_arr)
                            ->join('message_content c', 'c.id = m.mc_id')
                            ->where($cond_where)
                            ->order($cond_order)
                            ->limit($limit)
                            ->select();
        $result = array();
        if (is_array($messageContentList) && !empty($messageContentList)) {
            foreach($messageContentList as $key => $value)
            {
                $messageContentList[$key]['send_time'] = date('Y-m-d H:i', $value['send_time']);
            }
            $result['code'] = 1;
            $result['msg'] = '';
            $result['data'] = $messageContentList;
        } else {
            $result['code'] = 0;
            $result['msg'] = '';
            $result['data'] = array();
        }
        
        return $result;
    }
}